<?php
namespace addon\cms\logic;
use app\common\logic\LogicBase;
use \tpfcore\util\Tree;
use tpfcore\Core;
use tpfcore\helpers\StringHelper;
use think\Db;
use \think\Config;

class Category extends LogicBase
{
	private $childs=[];
	public function saveCategory($data){
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }
		$last_id=Core::loadAddonModel($this->name)->saveObject($data);
		if($last_id){
        	return [RESULT_SUCCESS, '操作成功', url("cms/category/index")];
        }else{
        	return [RESULT_ERROR, '操作失败', null];
        }
	}
	public function getCategory($data=[]){
		return self::getList($data);
	}
	public function delCategory($data){
		/*
			如下情况不能删除
			1、该分类下有文章
			2、该分数下还有其它子分类
		*/
		$logicPosts=Core::loadAddonModel('Posts','','controller');
		$listPosts=$logicPosts->getPostsList(["where"=>['cateid'=>$data['id']]]);
		if(count($listPosts)>0){
			return [RESULT_ERROR , '删除失败，该分类下还有文章', url("cms/category/index")];
		}
		
		$childs=self::getList(["where"=>['parentid'=>$data['id']]]);
		if(count($childs)>0){
			return [RESULT_ERROR , '删除失败，该分类下还有子分类', url("cms/category/index")];
		}

		return self::deleteObject(["id"=>$data['id']],true)?[RESULT_SUCCESS, '删除成功', url("cms/category/index")]:[RESULT_ERROR, '删除失败', url("cms/category/index")];
	}
	public function getCategoryListByid($data){
		return self::getOneObject($data);
	}
	public function getCategoryList($data){
		$result=self::getObject([],"*","sort ASC");
		$new_result=[];
		foreach ($result as $key => $value) {
			$new_result[$key]=$value->toArray();
		}
		//$assets_path=Config::get("template")['view_path'].DS.'assets';
        $tree = new Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($new_result as $n=> $r) {
        	$new_result[$n]['parentid_node'] = ($r['parentid']) ? ' class="child-of-node-' . $r['parentid'] . ' collapsed"' : 'class="expanded"';
            $new_result[$n]['manage'] = '<a href="' . url("cms/category/add", ["parentid" => $r['id']]) . '">添加分类</a> | <a href="' . url("cms/category/edit", ["id" => $r['id']]) . '">编辑分类</a> | <a href="' . url("cms/category/del", ["id" => $r['id']]). '" class="js-ajax-dialog-btn" data-msg="您确定要删除此数据吗？">删除分类</a> ';
            $new_result[$n]['isnav'] = $r['isnav'] ?  '<img src="/theme/backend/assets/images/yes.gif"/>': '<img src="/theme/backend/assets/images/no.gif"/>';
            $new_result[$n]['display'] = $r['display'] ? "显示" : "隐藏";

            $key=$r['channel_id'];

            $new_result[$n]['channel']="<font class=\"channel_$key\">".config("config.cms_channel")[$r['channel_id']]['name']."(".config("config.cms_channel")[$r['channel_id']]['key'].")</span>";
        }
       	
       	$url=url('cms/Category/ajaxdata');
        $tree->init($new_result);
        $str = "<tr id='node-\$id' \$parentid_node>
					<td>\$id</td>
					<td>\$spacer\$title</td>
					<td>\$channel</td>
					<td>\$isnav</td>
					<td style='padding-left:20px;'><input name='listorders[\$id]' data='Category|sort|id|\$id' type='text' size='3' value='\$sort' action='$url' class='input input-order ajax-text'></td>
				    <td>\$display</td>
					<td>\$manage</td>
				</tr>";
        $categorys = $tree->get_tree(0, $str);
		return $categorys;
	}
	public function getTreeCategory($data=[]){
		$parentid=empty($data['id'])?(empty($data['parentid'])?-1:$data['parentid']):$data['id'];
		if(!empty($data['id'])){
			$list=$this->getCategoryListByid(['id'=>$data['id']]);
			$parentid=$list->parentid;
		}
		if(!empty($data['cid'])){
			$parentid=$data['cid'];
		}
		if(!empty($data['parentid'])){
			$parentid=$data['parentid'];
		}
		$result=self::getObject([],"*","sort ASC");
		$new_result=[];
		foreach ($result as $key => $value) {
			unset($result[0]);
			$new_result[$value['id']]=$value->toArray();
		}
		
        $tree = new Tree();
        $tree->init($new_result);
        $str = "<option value='\$id' \$selected>\$spacer \$title</option>";
        $categorys = $tree->get_tree(0, $str,$parentid);
		return $categorys;
	}
	// 获取所有孩子节点ID
	public function getChildIds($parentid=0,$original=true){

		if($original) $this->childs[]=$parentid;
		
		$list=self::getList(['where'=>['parentid'=>$parentid]]);

		foreach ($list as $key => $value) {
			
			$this->childs[] = $value['id'];

			$this->getChildIds($value['id'],false);

		}

		return $this->childs;
	}
}